<?php
/**
 * 按HASH 生成页面
 *
 * @param  [type]
 * @return [type]
 */
function post_build_page_by_hash($hash = '') {
	require_once APP_PATH . '/post/model.php';
	//获取数据
	$post_data = post_model_get_by_hash($hash);
	//输出
	if ($post_data) {
		$post_html_path = post_build_page($post_data);
		return $post_html_path;
	} else {
		return false;
	}
}
/**
 * 生成静态页面
 * @param  array
 * @return [type]
 */
function post_build_page($post_data = array()) {
	$post_data = get_site_data($post_data);
	//解析markdown
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parser.php';
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parsedown.php';
	//创建解析器
	$parser = new Parsedown();
	$post_data['content'] = $parser->text($post_data['content']);
	$post_html_path = post_build_html($post_data);
	if ($post_html_path) {
		require_once APP_PATH . '/post/model.php';
		//更新数据库
		post_model_update_is_build_by_hash($post_data['hash'], 1);

		return $post_html_path;
	} else {
		return false;
	}
}
/**
 * 写入HTML文件
 * @param  string
 * @param  array
 * @return [type]
 */
function post_build_html($post_data = array()) {
	//获取发布时间
	$t = strtotime($post_data['publish_time']);
	$d = date("Y/m/d/", $t);
	//文件保存路径
	$html_file_dir = POST_HTML_PATH . $d;
	$html_file_path = $html_file_dir . $post_data['hash'] . '.html';
	//自动创建build path
	$html_file_path = filter_build_path($html_file_path);
	if (!$html_file_path) {
		return false;
	}
	$template = 'post.php';
	if (!empty($post_data['template'])) {
		$template = $post_data['template'];
	}
	$page_data = $post_data;
	ob_start();
	include APP_VIEW . '/' . $template; //引入模版文件
	file_put_contents($html_file_path, ob_get_contents()); //生成静态文件
	ob_clean();
	return $html_file_path;
}

function post_preview_page($post_data = array()) {
	//数据处理
	$post_data = get_site_data($post_data);
	//解析markdown
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parser.php';
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parsedown.php';
	//创建解析器
	$parser = new Parsedown();
	$post_data['content'] = $parser->text($post_data['content']);
	//模板处理
	$template = 'post.php';
	if (!empty($post_data['template'])) {
		$template = $post_data['template'];
	}
	$page_data = $post_data;
	include APP_VIEW . '/' . $template; //引入模版文件
}

function post_delete_html_by_hash($post_data = array()) {
	//获取发布时间
	$t = strtotime($post_data['publish_time']);
	$d = date("Y/m/d/", $t);
	//文件保存路径
	$html_file_dir = POST_HTML_PATH . $d;
	$html_file_path = $html_file_dir . $post_data['hash'] . '.html';
	if (file_exists($html_file_path)) {
		if (unlink($html_file_path)) {
			return true;
		} else {
			return false;
		}
	}
	return true;
}